<template>
  <el-drawer
    v-model="visible"
    :title="isEdit ? '编辑订单' : '新增订单'"
    size="60%"
    :before-close="handleClose"
    direction="rtl"
  >
    <el-form ref="orderFormRef" :model="orderForm" :rules="formRules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户" prop="customerId">
            <el-select
              v-model="orderForm.customerId"
              placeholder="请选择客户"
              filterable
              style="width: 100%"
              @change="handleCustomerChange"
            >
              <el-option
                v-for="customer in customerOptions"
                :key="customer.id"
                :label="customer.name"
                :value="customer.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交货日期" prop="deliveryDate">
            <el-date-picker
              v-model="orderForm.deliveryDate"
              type="date"
              placeholder="请选择交货日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 产品信息 -->
      <el-form-item label="产品信息">
        <div class="product-list">
          <div v-for="(product, index) in orderForm.products" :key="index" class="product-item">
            <div class="product-form-container">
              <el-row :gutter="10">
                <el-col :span="7">
                  <el-form-item label="产品名称" label-width="70px">
                    <el-input v-model="product.productName" placeholder="请输入产品名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="规格" label-width="70px">
                    <el-input v-model="product.specification" placeholder="请输入规格" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="单位" label-width="70px">
                    <el-input v-model="product.unit" placeholder="请输入单位" />
                  </el-form-item>
                </el-col>
                <el-col :span="4" class="delete-btn-col">
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                    @click="removeProduct(index)"
                  />
                </el-col>
              </el-row>
              <el-row :gutter="10" style="margin-top: 10px">
                <el-col :span="8">
                  <el-form-item label="数量" label-width="70px">
                    <el-input-number
                      v-model="product.quantity"
                      :min="1"
                      placeholder="请输入数量"
                      style="width: 100%"
                      @change="calculateProductTotal(index)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单价" label-width="70px">
                    <el-input-number
                      v-model="product.unitPrice"
                      :min="0"
                      :precision="2"
                      placeholder="请输入单价"
                      style="width: 100%"
                      @change="calculateProductTotal(index)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="小计" label-width="70px">
                    <el-input
                      :value="formatAmount(product.totalPrice)"
                      placeholder="自动计算"
                      readonly
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <el-button type="primary" :icon="Plus" @click="addProduct"> 添加产品 </el-button>
        </div>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="优惠金额">
            <el-input-number
              v-model="orderForm.discountAmount"
              :min="0"
              :precision="2"
              style="width: 100%"
              @change="calculateTotal"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单总额">
            <el-input :value="formatAmount(orderForm.totalAmount)" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实付金额">
            <el-input :value="formatAmount(orderForm.finalAmount)" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注">
        <el-input
          v-model="orderForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { formatAmount } from '@/utils'
import type { Customer } from '@/types'

interface OrderFormData {
  id: string
  customerId: string
  customerName: string
  deliveryDate: string
  products: Array<{
    id: string
    productId: string
    productName: string
    specification: string
    quantity: number
    unit: string
    unitPrice: number
    totalPrice: number
    fabricType: string
    color: string
    width: number
    weight: number
  }>
  totalAmount: number
  discountAmount: number
  finalAmount: number
  status: 'pending' | 'confirmed' | 'production' | 'shipped' | 'delivered' | 'cancelled'
  paymentStatus: 'unpaid' | 'partial' | 'paid' | 'refunded'
  remark: string
}

interface Props {
  modelValue: boolean
  isEdit: boolean
  orderData?: OrderFormData | null
  customerOptions: Customer[]
  submitLoading: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', data: OrderFormData): void
}

const props = withDefaults(defineProps<Props>(), {
  orderData: null,
  submitLoading: false,
})

const emit = defineEmits<Emits>()

const orderFormRef = ref<FormInstance>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

// 订单表单数据
const orderForm = reactive<OrderFormData>({
  id: '',
  customerId: '',
  customerName: '',
  deliveryDate: '',
  products: [
    {
      id: '',
      productId: '',
      productName: '',
      specification: '',
      quantity: 1,
      unit: '米',
      unitPrice: 0,
      totalPrice: 0,
      fabricType: '',
      color: '',
      width: 0,
      weight: 0,
    },
  ],
  totalAmount: 0,
  discountAmount: 0,
  finalAmount: 0,
  status: 'pending',
  paymentStatus: 'unpaid',
  remark: '',
})

// 表单验证规则
const formRules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  deliveryDate: [{ required: true, message: '请选择交货日期', trigger: 'change' }],
}

// 重置表单
const resetForm = () => {
  Object.assign(orderForm, {
    id: '',
    customerId: '',
    customerName: '',
    deliveryDate: '',
    products: [
      {
        id: '',
        productId: '',
        productName: '',
        specification: '',
        quantity: 1,
        unit: '米',
        unitPrice: 0,
        totalPrice: 0,
        fabricType: '',
        color: '',
        width: 0,
        weight: 0,
      },
    ],
    totalAmount: 0,
    discountAmount: 0,
    finalAmount: 0,
    status: 'pending' as const,
    paymentStatus: 'unpaid' as const,
    remark: '',
  })
  orderFormRef.value?.clearValidate()
}

// 监听订单数据变化，用于编辑时填充表单
watch(
  () => props.orderData,
  (newData) => {
    if (newData) {
      Object.assign(orderForm, newData)
    } else {
      resetForm()
    }
  },
  { immediate: true },
)

// 计算产品小计
const calculateProductTotal = (index: number) => {
  const product = orderForm.products[index]
  product.totalPrice = product.quantity * product.unitPrice
  calculateTotal()
}

// 计算订单总额
const calculateTotal = () => {
  orderForm.totalAmount = orderForm.products.reduce((sum, product) => sum + product.totalPrice, 0)
  orderForm.finalAmount = orderForm.totalAmount - (orderForm.discountAmount || 0)
}

// 添加产品
const addProduct = () => {
  orderForm.products.push({
    id: '',
    productId: '',
    productName: '',
    specification: '',
    quantity: 1,
    unit: '米',
    unitPrice: 0,
    totalPrice: 0,
    fabricType: '',
    color: '',
    width: 0,
    weight: 0,
  })
}

// 移除产品
const removeProduct = (index: number) => {
  if (orderForm.products.length > 1) {
    orderForm.products.splice(index, 1)
    calculateTotal()
  }
}

// 客户变化处理
const handleCustomerChange = (customerId: string) => {
  const customer = props.customerOptions.find((c) => c.id === customerId)
  if (customer) {
    orderForm.customerName = customer.name
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!orderFormRef.value) return

  try {
    await orderFormRef.value.validate()
    emit('submit', { ...orderForm })
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 暴露重置表单方法
defineExpose({
  resetForm,
})
</script>

<style scoped>
.product-list {
  .product-item {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fafafa;
  }
}

.delete-btn-col {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 32px;
}

.product-form-container {
  position: relative;
}
</style>
